﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using StateGrid.User;
using StateGrid.MDBservice;

namespace StateGrid.UI
{
    /// <summary>
    /// Interaction logic for TranditionWizard.xaml
    /// </summary>
    public partial class TraditionWizard : UserControl
    {
        enum OPERATIONSTEP
        {
            validateSymlTableName = 0,
            validateSymlTableColumn,
            formatSymlData,
            removeLocalSymlDuplicate,
            removeServerSymlDuplicate,
            addSymlRecords,
            validateTableName,
            validateTableColumn,
            formatData,
            removeLocalDuplicate,
            removeServerDuplicate,
            addRecords,
            done
        }

        // iRepos 用来指向当前操作的文库类
        private MDBservice.MDBservice iRepos;
        /// <summary>
        /// 当前操作进行到的步骤
        /// </summary>
        private OPERATIONSTEP opStep;
        

        /// <summary>
        /// 选择数据库文件的文件选择框
        /// </summary>
        private System.Windows.Forms.OpenFileDialog fileSource;
        /// <summary>
        /// 选择全文的文件夹选择框
        /// </summary>
        private System.Windows.Forms.FolderBrowserDialog folderSource;
        
        public TraditionWizard(MDBservice.MDBservice repos, User.User user)
        {
            InitializeComponent();

            iRepos = repos;
            iRepos.user = user;
            lblTitle.Content = iRepos.title;
            this.txtSourceFolder.Text = "";
            this.txtSourceFile.Text = "";

            // operatePanel.Visibility = Visibility.Hidden;
            // scrollViewerLog.Visibility = Visibility.Hidden;
            if (iRepos.id == "zhongwenhuiyi" || iRepos.id == "waiwenhuiyi")
                wrapSYML.Visibility = Visibility.Visible;
              
            // setButtonDisable();
            // setSymlButtonDisable();
            
            this.btnOnekey.IsEnabled = false;
        }

        /// <summary>
        /// 将所有按钮设置为Disable
        /// </summary>
        private void setButtonDisable()
        {
            this.btnValidateTableName.IsEnabled = false;
            this.btnValidateTableColumn.IsEnabled = false;
            this.btnValidateColumnContent.IsEnabled = false;
            this.btnRemoveDuplicate.IsEnabled = false;
            this.btnFindDuplicate.IsEnabled = false;
            this.btnAddRecord.IsEnabled = false;
        }

        /// <summary>
        /// 将索引目录相关所有按钮设置为Disable
        /// </summary>
        private void setSymlButtonDisable()
        {
            this.btnValidateSymlTableName.IsEnabled = false;
            this.btnValidateSymlTableColumn.IsEnabled = false;
            this.btnValidateSymlColumnContent.IsEnabled = false;
            this.btnRemoveSymlDuplicate.IsEnabled = false;
            this.btnFindSymlDuplicate.IsEnabled = false;
            this.btnAddSymlRecord.IsEnabled = false;
        }

        private void btnSourceFile_Click(object sender, RoutedEventArgs e)
        {
            if (null == this.fileSource)
            {
                this.fileSource = new System.Windows.Forms.OpenFileDialog();
            }
            this.fileSource.Filter = "MDB文件(*.mdb)|*.mdb";
            this.fileSource.ShowDialog();
            this.txtSourceFile.Text = this.fileSource.FileName;

        }

        private void btnSourceFolder_Click(object sender, RoutedEventArgs e)
        {
            if (null == this.folderSource)
            {
                this.folderSource = new System.Windows.Forms.FolderBrowserDialog();
            }
            this.folderSource.ShowDialog();
            this.txtSourceFolder.Text = this.folderSource.SelectedPath;
        }

        private void txtSourceFile_TextChanged(object sender, TextChangedEventArgs e)
        {
            setButtonDisable();
            iRepos.DataBasePath = txtSourceFile.Text;
            if (!String.Empty.Equals(txtSourceFile.Text) && !String.Empty.Equals(txtSourceFolder.Text))
            {
                if (iRepos.id.Equals("zhongwenhuiyi") || iRepos.id.Equals("waiwenhuiyi"))
                {
                    this.btnValidateSymlTableName.IsEnabled = true;
                    this.opStep = OPERATIONSTEP.validateSymlTableName;
                }
                else
                {
                    this.btnValidateTableName.IsEnabled = true;
                    this.opStep = OPERATIONSTEP.validateTableName;
                }
                this.btnOnekey.IsEnabled = true;
            }
        }

        private void txtSourceFolder_TextChanged(object sender, TextChangedEventArgs e)
        {
            setButtonDisable();
            iRepos.fileFolder = txtSourceFolder.Text;
            if (!String.Empty.Equals(txtSourceFile.Text) && !String.Empty.Equals(txtSourceFolder.Text))
            {
                if (iRepos.id.Equals("zhongwenhuiyi") || iRepos.id.Equals("waiwenhuiyi"))
                {
                    this.btnValidateSymlTableName.IsEnabled = true;
                    this.opStep = OPERATIONSTEP.validateSymlTableName;
                }
                else
                {
                    this.btnValidateTableName.IsEnabled = true;
                    this.opStep = OPERATIONSTEP.validateTableName;
                }
                this.btnOnekey.IsEnabled = true;
            }
        }

        private void btnValidateTableName_Click(object sender, RoutedEventArgs e)
        {
            String err = iRepos.validateTableName(iRepos.formatPmTableName, txtSourceFile.Text, txtSourceFolder.Text);
            if (String.Empty.Equals(err))
            {
                iRepos.hasFormatTable = true;
                scrollViewerLog.Content += "验证表名成功！存在规范后的表" + iRepos.formatPmTableName + "，从该表中读取数据\n";
            }
            else
            {
                err = iRepos.validateTableName(iRepos.pmTableName);
                if (String.Empty.Equals(err))
                {
                    iRepos.hasFormatTable = false;
                    scrollViewerLog.Content += "验证表名成功！从原始数据表" + iRepos.pmTableName + "中读取数据\n";
                    /* 这里设置检查是否支持从原始数据里提取篇名信息 */
                    if (!iRepos.id.Equals("zhongwenqikan")
                        && !iRepos.id.Equals("waiwenqikan"))
                    {
                        err = "当前文库不支持从原始数据里提取篇名！\n";
                        scrollViewerLog.Content += err;
                        return;
                    }
                }
                else
                {
                    scrollViewerLog.Content += err;
                    return;
                }
            }
            setButtonDisable();
            this.btnValidateTableColumn.IsEnabled = true;
            this.opStep = OPERATIONSTEP.validateTableColumn;
        }

        private void btnValidateTableColumn_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            List<ColumnError> errs = iRepos.validateTableColums();
            if (errs != null && errs.Count != 0)
            {
                foreach (ColumnError clmErr in errs)
                {
                    scrollViewerLog.Content += clmErr.ToString();
                }
            }
            else
            {
                setButtonDisable();
                this.btnValidateColumnContent.IsEnabled = true;
                this.opStep = OPERATIONSTEP.formatData;
            }
            System.Windows.Forms.Cursor.Current = oldCursor;
        }

        private void formatData()
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            if (iRepos.formatData(scrollViewerLog, progressBar1))
                this.btnRemoveDuplicate.Dispatcher.Invoke(new Action(() => { this.btnRemoveDuplicate.IsEnabled = true; }));
            this.opStep = OPERATIONSTEP.removeLocalDuplicate;
            System.Windows.Forms.Cursor.Current = oldCursor;
        }

        private void btnValidateColumnContent_Click(object sender, RoutedEventArgs e)
        {
            setButtonDisable();
            new System.Threading.Thread(new System.Threading.ThreadStart(formatData)).Start();
        }

        private void removeDuplicate()
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            iRepos.removeLocalDuplicate(scrollViewerLog, progressBar1);
            this.btnFindDuplicate.Dispatcher.Invoke(new Action(() => { this.btnFindDuplicate.IsEnabled = true; }));
            this.opStep = OPERATIONSTEP.removeServerDuplicate;
            System.Windows.Forms.Cursor.Current = oldCursor;
        }
        private void btnRemoveDuplicate_Click(object sender, RoutedEventArgs e)
        {
            setButtonDisable();
            new System.Threading.Thread(new System.Threading.ThreadStart(removeDuplicate)).Start();
        }

        private void findDuplicate()
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            iRepos.removeServerDuplicate(scrollViewerLog, progressBar1);
            this.btnAddRecord.Dispatcher.Invoke(new Action(() => { this.btnAddRecord.IsEnabled = true; }));
            this.opStep = OPERATIONSTEP.addRecords;
            System.Windows.Forms.Cursor.Current = oldCursor;
        }

        private void btnFindDuplicate_Click(object sender, RoutedEventArgs e)
        {
            setButtonDisable();
            new System.Threading.Thread(new System.Threading.ThreadStart(findDuplicate)).Start();
        }

        private void addRecord()
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            iRepos.addRecords(scrollViewerLog, progressBar1);
            System.Windows.Forms.Cursor.Current = oldCursor;
            this.opStep = OPERATIONSTEP.done;
            System.Windows.MessageBox.Show("上传数据完毕!\n");
        }

        private void btnAddRecord_Click(object sender, RoutedEventArgs e)
        {
            setButtonDisable();
            new System.Threading.Thread(new System.Threading.ThreadStart(addRecord)).Start();
        }

        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            txtSourceFile.Text = String.Empty;
            txtSourceFolder.Text = String.Empty;

            setButtonDisable();
            setSymlButtonDisable();
            this.btnOnekey.IsEnabled = false;
            progressBar1.Value = 0;
            iRepos.clear();
        }

        private void btnValidateSymlTableName_Click(object sender, RoutedEventArgs e)
        {
            String err = iRepos.validateTableName(iRepos.formatPmTableName, txtSourceFile.Text, txtSourceFolder.Text);
            if (String.Empty.Equals(err))
            {
                iRepos.hasFormatTable = true;
                scrollViewerLog.Content += "验证表名成功！存在规范后的表" + iRepos.symlTableName + "，从该表中读取数据\n";
            }
            else
            {
                scrollViewerLog.Content += err;
                return;
            }
            setSymlButtonDisable();
            this.btnValidateSymlTableColumn.IsEnabled = true;
            this.opStep = OPERATIONSTEP.validateSymlTableColumn;
        }

        private void btnValidateSymlTableColumn_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            List<ColumnError> errs = iRepos.validateTableColums(false);
            if (errs != null && errs.Count != 0)
            {
                foreach (ColumnError clmErr in errs)
                {
                    scrollViewerLog.Content += clmErr.ToString();
                }
            }
            else
            {
                setSymlButtonDisable();
                this.btnValidateSymlColumnContent.IsEnabled = true;
                this.opStep = OPERATIONSTEP.formatSymlData;
            }
            System.Windows.Forms.Cursor.Current = oldCursor;
        }

        private void formatSyml()
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            if (iRepos.formatSyml(scrollViewerLog, progressBar1))
                this.btnRemoveSymlDuplicate.Dispatcher.Invoke(new Action(() => { this.btnRemoveSymlDuplicate.IsEnabled = true; }));
            this.opStep = OPERATIONSTEP.removeLocalSymlDuplicate;
            System.Windows.Forms.Cursor.Current = oldCursor;
        }

        private void btnValidateSymlColumnContent_Click(object sender, RoutedEventArgs e)
        {
            setSymlButtonDisable();
            new System.Threading.Thread(new System.Threading.ThreadStart(formatSyml)).Start();
        }

        private void removeSymlDuplicate()
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            iRepos.removeLocalSymlDuplicate(scrollViewerLog, progressBar1);
            this.btnFindSymlDuplicate.Dispatcher.Invoke(new Action(() => { this.btnFindSymlDuplicate.IsEnabled = true; }));
            this.opStep = OPERATIONSTEP.removeServerSymlDuplicate;
            System.Windows.Forms.Cursor.Current = oldCursor;
        }

        private void btnRemoveSymlDuplicate_Click(object sender, RoutedEventArgs e)
        {
            setSymlButtonDisable();
            new System.Threading.Thread(new System.Threading.ThreadStart(removeSymlDuplicate)).Start();
        }

        private void findSymlDuplicate()
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            iRepos.removeServerSymlDuplicate(scrollViewerLog, progressBar1);
            this.btnAddSymlRecord.Dispatcher.Invoke(new Action(() => { this.btnAddSymlRecord.IsEnabled = true; }));
            this.opStep = OPERATIONSTEP.addSymlRecords;
            System.Windows.Forms.Cursor.Current = oldCursor;
        }

        private void btnFindSymlDuplicate_Click(object sender, RoutedEventArgs e)
        {
            setSymlButtonDisable();
            new System.Threading.Thread(new System.Threading.ThreadStart(findSymlDuplicate)).Start();
        }

        private void addSymlRecord()
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            iRepos.addSymlRecords(scrollViewerLog, progressBar1);
            this.btnValidateTableName.Dispatcher.Invoke(new Action(() => { this.btnValidateTableName.IsEnabled = true; }));
            this.opStep = OPERATIONSTEP.validateTableName;
            System.Windows.Forms.Cursor.Current = oldCursor;
        }

        private void btnAddSymlRecord_Click(object sender, RoutedEventArgs e)
        {
            setSymlButtonDisable();
            new System.Threading.Thread(new System.Threading.ThreadStart(addSymlRecord)).Start();
        }

        public void logInfo(ScrollViewer logViewer, String info)
        {
            logViewer.Dispatcher.Invoke(new Action(() => { logViewer.Content += info; }));
        }

        private void onekeyThread()
        {
            String err;
            List<ColumnError> errs;
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            String srcFile, srcFolder;
            srcFile = String.Empty;
            srcFolder = String.Empty;
            txtSourceFile.Dispatcher.Invoke(new Action(() => { srcFile = txtSourceFile.Text; }));
            txtSourceFolder.Dispatcher.Invoke(new Action(() => { srcFolder = txtSourceFolder.Text; }));
            while (String.Empty.Equals(srcFile) || String.Empty.Equals(srcFolder)) ;

            if (iRepos.id.Equals("zhongwenhuiyi") || iRepos.id.Equals("waiwenhuiyi"))
            {
                if (this.opStep <= OPERATIONSTEP.validateSymlTableName)
                {
                    logInfo(scrollViewerLog, "正在验证索引目录表名\n");
                    err = iRepos.validateTableName(iRepos.formatPmTableName, srcFile, srcFolder);
                    if (String.Empty.Equals(err))
                    {
                        iRepos.hasFormatTable = true;
                        logInfo(scrollViewerLog, "验证表名成功！存在规范后的表" + iRepos.symlTableName + "，从该表中读取数据\n");
                    }
                    else
                    {
                        logInfo(scrollViewerLog, err);
                        return;
                    }
                }

                if (this.opStep <= OPERATIONSTEP.validateSymlTableColumn)
                {
                    logInfo(scrollViewerLog, "正在验证索引目录字段\n");
                    errs = iRepos.validateTableColums(false);
                    if (errs != null && errs.Count != 0)
                    {
                        foreach (ColumnError clmErr in errs)
                        {
                            logInfo(scrollViewerLog, clmErr.ToString());
                        }
                        return;
                    }
                }
                if (this.opStep <= OPERATIONSTEP.formatSymlData)
                    iRepos.formatSyml(scrollViewerLog, progressBar1);
                if (this.opStep <= OPERATIONSTEP.removeLocalSymlDuplicate)
                    iRepos.removeLocalSymlDuplicate(scrollViewerLog, progressBar1);
                if (this.opStep <= OPERATIONSTEP.removeServerSymlDuplicate)
                    iRepos.removeServerSymlDuplicate(scrollViewerLog, progressBar1);
                if (this.opStep <= OPERATIONSTEP.addSymlRecords)
                    iRepos.addSymlRecords(scrollViewerLog, progressBar1);
                // 需要合并到一个线程里去，否则并行执行有关联的代码
            }

            if (this.opStep <= OPERATIONSTEP.validateTableName)
            {
                logInfo(scrollViewerLog, "正在验证表名\n");
                err = iRepos.validateTableName(iRepos.formatPmTableName, srcFile, srcFolder);
                if (String.Empty.Equals(err))
                {
                    iRepos.hasFormatTable = true;
                    logInfo(scrollViewerLog, "验证表名成功！存在规范后的表" + iRepos.formatPmTableName + "，从该表中读取数据\n");
                }
                else
                {
                    err = iRepos.validateTableName(iRepos.pmTableName);
                    if (String.Empty.Equals(err))
                    {
                        iRepos.hasFormatTable = false;
                        logInfo(scrollViewerLog, "验证表名成功！从原始数据表" + iRepos.pmTableName + "中读取数据\n");
                        if (!iRepos.id.Equals("zhongwenqikan")
                            && !iRepos.id.Equals("waiwenqikan"))
                        {
                            err = "当前文库不支持从原始数据里提取篇名！\n";
                            logInfo(scrollViewerLog, err);
                            return;
                        }
                    }
                    else
                    {
                        logInfo(scrollViewerLog, err);
                        return;
                    }
                }
            }
            if (this.opStep <= OPERATIONSTEP.validateTableColumn)
            {
                logInfo(scrollViewerLog, "正在验证字段\n");
                errs = iRepos.validateTableColums();
                if (errs != null && errs.Count != 0)
                {
                    foreach (ColumnError clmErr in errs)
                    {
                        logInfo(scrollViewerLog, clmErr.ToString());
                    }
                    return;
                }
            }
            if (this.opStep <= OPERATIONSTEP.formatData)
                iRepos.formatData(scrollViewerLog, progressBar1);
            if (this.opStep <= OPERATIONSTEP.removeLocalDuplicate)
                iRepos.removeLocalDuplicate(scrollViewerLog, progressBar1);
            if (this.opStep <= OPERATIONSTEP.removeServerDuplicate)
                iRepos.removeServerDuplicate(scrollViewerLog, progressBar1);
            if (this.opStep <= OPERATIONSTEP.addRecords)
                iRepos.addRecords(scrollViewerLog, progressBar1);
            this.opStep = OPERATIONSTEP.done;
            System.Windows.MessageBox.Show("上传数据完毕!\n");
            System.Windows.Forms.Cursor.Current = oldCursor;
        }

        private void btnOnekey_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.Cursor oldCursor = System.Windows.Forms.Cursor.Current;
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            setSymlButtonDisable();
            setButtonDisable();
            this.btnOnekey.IsEnabled = false;
            new System.Threading.Thread(new System.Threading.ThreadStart(onekeyThread)).Start();
        }
    }


}
